import Vue from "vue"; // 导入vue
import Main from "./index.vue"; // 导入组件
import { getToken } from "@/utils/auth";
// 将组件作为参数，使用vue提供的全局方法，创建一个构造函数
let DrawerConstructor = Vue.extend(Main);

let instance;
// 上传框默认配置
const uploadDefaultConfig = {
    uploadFileUrl: "/system/oss/upload", // 上传文件服务器地址 以#开头的将认定为自定义上传 el:"#a/upload" || "#/a/upload"
    headers: {
        Authorization: "Bearer " + getToken(),
    },
    method: "post",
    limit: 5, // 限制数量
    fileSize: 20, // MB
    fileType: ["doc", "xls", "ppt", "txt", "pdf", "png", "jpg", "jpeg"],
    multiple: true, // 是否支持多选
    isShowTip: true, // 是否显示提示
    tip: "", // 提示，支持html
    params: {}, // 将跟随上传一起传入data
    templateUrl: "", // 模板地址
    templateName: "", // 模板名称
    errorUrl: "", // 下载错误数据地址
};

const Drawer = function (config = {}) {
    // dialog框配置
    let {
        title = "",
        showFooter = true,
        toastSureBtn = "确认",
        showtoastSureBtn = true,
        toastFailBtn = "返回",
        showtoastFailBtn = true,
        showResult = true, // 是否显示上传结果列表
        showErrorFeedback = true, // 是否显示 下载错误日志
        uploadConfig = {}, // 上传框配置
    } = config;
    uploadConfig.title = title;
    let uploadConfigMerge = Object.assign(uploadDefaultConfig, uploadConfig);
    return new Promise((resolve, reject) => {
        // 初始化实例，此时instance是一个组件实例，但未初始化未完成
        instance = new DrawerConstructor({
            data: {
                title,
                showFooter,
                toastSureBtn,
                showtoastSureBtn,
                toastFailBtn,
                showtoastFailBtn,
                uploadConfig: uploadConfigMerge,
                showResult,
                showErrorFeedback,
            },
            methods: {
                Select: (res) => {
                    // unmount();
                    resolve(res);
                },
                Cancel: (err = "close") => {
                    unmount();
                    reject(err);
                },
            },
        });
        // 卸载组件
        const unmount = () => {
            instance.visible = false;
        };
        // 完成初始化
        instance.$mount();

        // 将组件添加到根节点body
        document.body.appendChild(instance.$el);
        instance.visible = true;
    });
};

export default Drawer;
